package com.lyj.io.aspect;

import com.google.gson.Gson;
import com.lyj.io.annotation.SysLogAnnotation;
import com.lyj.io.common.utils.HttpContextUtils;
import com.lyj.io.common.utils.IPUtils;
import com.lyj.io.module.sys.entity.SysLog;
import com.lyj.io.module.sys.entity.SysUser;
import com.lyj.io.module.sys.service.SysLogService;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 系统日志切面处理类
 * @author:liyajie
 * @createTime:2022/1/5 11:23
 * @version:1.0
 */
@Aspect
@Component
public class SysLogAspect {
	@Autowired
	private SysLogService sysLogService;

	@Pointcut("@annotation(com.lyj.io.annotation.SysLogAnnotation)")
	public void logPointCut() {

	}

	@Around("logPointCut()")
	public Object around(ProceedingJoinPoint point) throws Throwable {
		long beginTime = System.currentTimeMillis();
		//执行方法
		Object result = point.proceed();
		//执行时长(毫秒)
		long time = System.currentTimeMillis() - beginTime;
		//保存日志
		saveSysLog(point, time, result);
		return result;
	}

	private void saveSysLog(ProceedingJoinPoint joinPoint, long time, Object result) throws UnsupportedEncodingException {
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();

		SysLog sysLog = new SysLog();
		SysLogAnnotation sysLogAnnotation = method.getAnnotation(SysLogAnnotation.class);
		if(sysLogAnnotation != null){
			//注解上的描述
			sysLog.setOperation(sysLogAnnotation.value());
		}
		//请求的方法名
		String className = joinPoint.getTarget().getClass().getName();
		String methodName = signature.getName();
		sysLog.setMethod(className + "." + methodName + "()");
		//请求的参数
		Object[] args = joinPoint.getArgs();
		try{
			String params = new Gson().toJson(args);
			sysLog.setParams(params);
		}catch (Exception e){
			e.printStackTrace();
		}
		//获取request
		HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
		//设置IP地址
		sysLog.setIp(IPUtils.getIpAddr(request));
		//用户名
		// String username = ((SysUser) SecurityUtils.getSubject().getPrincipal()).getUsername();
		String username = request.getHeader("admin-token");
		sysLog.setUsername(URLDecoder.decode(username, "UTF-8"));
		sysLog.setTime(time);
		sysLog.setCreateDate(new Date());
		sysLog.setResult(new Gson().toJson(result));
		//保存系统日志
		sysLogService.save(sysLog);
	}

	/**
	 * 将cookie封装成map
	 * @author: liyajie
	 * @date: 2022/1/5 17:21
	 * @param request
	 * @return java.util.Map<java.lang.String,javax.servlet.http.Cookie>
	 * @exception:
	 * @update:
	 * @updatePerson:
	 **/
	private static Map<String, Cookie> readCookieMap(HttpServletRequest request){
		Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
		Cookie[] cookies = request.getCookies();        //获取所有的cookie值
		if(cookies != null){
			for (Cookie cookie : cookies){
				cookieMap.put(cookie.getName(),cookie);
			}
		}
		return cookieMap;
	}
}
